package com.leyou.order.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.order.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class UserInfoInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtProperties props;

    //ThreadLocal只有当前线程，可以访问
    private ThreadLocal<UserInfo> tl = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();

        //如果是微信的请求则直接放行
        if ("/pay/wx/notify".startsWith(requestURI)){
            return true;
        }

        try {
            String token = CookieUtils.getCookieValue(request, props.getUser().getCookieName());

            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, props.getPublicKey(), UserInfo.class);

            //把用户的信息加入threadLocal
            tl.set(infoFromToken.getInfo());

            return true;
        } catch (Exception e) {
            response.setStatus(403);
            return false;
        }

    }

    public UserInfo getUserInfo() {
        return tl.get();
    }



    //最终执行,保证tl中的内容是空的干净的
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tl.remove();
    }
}
